<template>
    <a-modal
        title="新技术应用情况上报"
        :visible="visible"
        :class="state !== 0 ? 'normal-modal' : 'large-modal'"
        @cancel="handleCancel"
    >
        <div class="about-master-container">
            <a-form>
                <a-row :gutter="24">
                    <a-form-model ref="form" :model="localForm" :rules="rules">
                        <a-col v-if="state === 0" span="6">
                            <a-card v-loading="getTreeLoading">
                                <title-name title="新技术类型" />
                                <a-input-search style="margin-bottom: 8px" @change="onChange" />
                                <div :style="'height: calc('+GET_REDRESS_PERCENTAGE+'vh - 400px); overflow: auto'">
                                    <a-tree
                                        :expanded-keys="expandedKeys"
                                        :auto-expand-parent="autoExpandParent"
                                        :tree-data="treeData"
                                        :selected-keys="selectedKeys"
                                        @select="onSelect"
                                        @expand="onExpand"
                                    >
                                        <template slot="title" slot-scope="{ title }">
                                            <span v-if="title.indexOf(searchValue) > -1">
                                                {{ title.substr(0, title.indexOf(searchValue)) }}
                                                <span style="color: #f50">{{ searchValue }}</span>
                                                {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                                            </span>
                                            <span v-else>{{ title }}</span>
                                        </template>
                                    </a-tree>
                                </div>
                            </a-card>
                        </a-col>
                        <a-col :span="state !== 0 ? 24 : 18">
                            <a-row>
                                <a-col span="24">
                                    <a-form-model-item label="应用技术：" prop="technicalId">
                                        <a-select
                                            v-if="state === 0"
                                            v-model="localForm.technicalId"
                                            placeholder="请选择"
                                            @change="selectChange"
                                        >
                                            <a-icon
                                                v-if="getTreeLoading"
                                                slot="suffixIcon"
                                                style="color: #096dd9"
                                                type="loading"
                                            />
                                            <a-select-option
                                                v-for="item in technologyTemplateList"
                                                :key="item.technicalId"
                                                :value="item.technicalId"
                                            >
                                              {{item.number + ' ' + item.technicalName }}
                                            </a-select-option>
                                        </a-select>
                                        <b-input v-else v-model="localForm.technicalName" disabled />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="24">
                                    <a-form-model-item label="所属单位：" prop="projectId">
                                        <org-tree-select
                                                v-if="state !== 2"
                                                v-model="localForm.projectId"
                                                :disabled="state === 2"
                                                is-need-auth
                                                is-auto-select-first
                                                :is-query-projec-detail="false"
                                                @select="selectOrg"
                                        />
                                        <b-input v-else v-model="localForm.projectName" disabled />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="12">
                                    <a-form-model-item label="应用工程量：" prop="applicationNumber">
                                        <BaseInputNumber
                                            v-model.trim="localForm.applicationNumber"
                                            :min="0"
                                            placeholder="请输入应用工程量"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="12">
                                    <a-form-model-item :label="`实物量（${selectTemplate.entityMeasureUnit}）`" prop="entityMeasure">
                                        <BaseInputNumber
                                            v-model.trim="localForm.entityMeasure"
                                            :max-length="9"
                                            placeholder="实物量"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="24">
                                    <a-form-model-item label="应用部位" prop="applicationSite">
                                        <BaseInput v-model.trim="localForm.applicationSite" placeholder="请输入" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="24">
                                    <a-form-model-item label="应用情况" prop="applicationSituation">
                                        <BaseInput v-model.trim="localForm.applicationSituation" placeholder="请输入" />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="12">
                                    <a-form-model-item label="投入经费（万元）：" prop="investmentOutlay">
                                        <BaseInputNumber
                                            v-model.trim="localForm.investmentOutlay"
                                            :max="10000000000"
                                            :min="0"
                                            :precision="6"
                                            placeholder="请输入投入经费"
                                        />
                                    </a-form-model-item>
                                </a-col>

                                <a-col span="12">
                                    <a-form-model-item label="生产效益（万元）：" prop="productionBenefit">
                                        <BaseInputNumber
                                            v-model.trim="localForm.productionBenefit"
                                            :max="10000000000"
                                            :min="0"
                                            :precision="6"
                                            placeholder="请输入生产效益"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="24">
                                    <a-form-model-item label="备注" >
                                        <BaseInput
                                            v-model.trim="localForm.remark"

                                            placeholder="请输入备注"
                                        />
                                    </a-form-model-item>
                                </a-col>
                                <a-col span="24">
                                    <a-form-model-item label="附件上传" prop="fileArrays">
                                        <upload-list
                                            class="limitText"
                                            v-if="visible && state !== 2"
                                            business-code="STM01"
                                            :upload-arrys.sync="localForm.fileArrays"
                                            :count="5"
                                            multiple
                                            @fileArrysData="$refs.form.validateField('fileArrays')"
                                        />
                                        <file-link v-else :file-list="localForm.fileArrays" />
                                    </a-form-model-item>
                                    <span v-if="state !== 2" class="del_btn" style="margin-left: 95px"
                                        >提示：上传附件为应用新技术对应照片，每张照片以 小项编号 技术名称 地区+项目名称</span
                                    >
                                </a-col>
                            </a-row>
                        </a-col>
                    </a-form-model>
                </a-row>
            </a-form>
        </div>
        <template slot="footer">
            <template v-if="state !== 2">
                <a-button
                    :disabled="confirmLoading[1]"
                    :loading="confirmLoading[0]"
                    type="primary"
                    @click.stop="handleOk(0)"
                >
                    保存
                </a-button>
                <a-button
                    :disabled="confirmLoading[0]"
                    :loading="confirmLoading[1]"
                    type="primary"
                    @click.stop="handleOk(1)"
                >
                    提交
                </a-button>
            </template>
            <a-button :type="state === 2 ? 'primary' : 'default'" @click.stop="handleCancel">
                {{ state === 2 ? '关闭' : '取消' }}
            </a-button>
        </template>
        <selectApprover :businessId="businessId"  :processConfig="setProcessConfig" :isCloseUpper="false" @close="closeSelectApprover"></selectApprover>
    </a-modal>
</template>

<script>
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import { addTechnology, editTechnology, getTechnologyTemplate, treeList } from '@/api/technology'
import UploadList from '@/components/UploadList'
import {mapGetters } from 'vuex'

export default {
    name: 'a' + Date.now(),
    components: {
        SelectSubCompany,
        SelectProject,
        UploadList
    },
    props: {
        visible: {
            type: Boolean,
            required: true
        },
        state: {
            type: Number,
            default: 0
        },
        form: {
            type: Object,
            default() {
                return null
            }
        }
    },
    data() {
        return {
            selectTechnology: true,
            technologyTemplateList: [],
            getTreeLoading: false,
            confirmLoading: { 0: false, 1: false },
            selectTemplate:{entityMeasureUnit:'套'},
            localForm: { technicalId: '' },
            rules: {
                treeId: [{ required: true, message: '请选择新技术类型', trigger: 'change' }],
                technicalId: [{ required: true, message: '请选择应用技术', trigger: 'change' }],
                branchCompanyId: [{ required: true, message: '请选择所属分公司', trigger: 'change' }],
                projectId: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
                applicationNumber: [{ required: true, message: '请输入应用工程量', trigger: 'blur' }],
                entityMeasure: [{ required: true, message: '请输入实物量（套）', trigger: 'blur' }],
                investmentOutlay: [{ required: true, message: '请输入投入经费（万元）', trigger: 'blur' }],
                productionBenefit: [{ required: true, message: '请输入生产效益（万元）', trigger: 'blur' }],
                applicationSite: [{ required: true, message: '请输入应用部位', trigger: 'blur' }],
                applicationSituation: [{ required: true, message: '请输入应用情况', trigger: 'blur' }],
                fileArrays: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }]
            },

            treeData: [],
            selectedKeys: [],
            replaceFields: {
                children: 'children',
                title: 'name',
                key: 'id'
            },
            expandedKeys: [],
            expandedKeysTemp: [],
            searchValue: '',
            autoExpandParent: true,
            dataList: [],
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    computed: {
        ...mapGetters(['GET_REDRESS_PERCENTAGE'])
    },
    watch: {
        visible(newVal) {
            if (newVal && this.state === 0) {
                this.getTree()
            }
            if (this.form) {
                this.localForm = this.$assign(this.localForm, this.form)
                if(this.localForm.fileArrays&&this.localForm.fileArrays.length) {
                    if(this.localForm.fileArrays[0] == null) {
                        this.localForm.fileArrays = []
                    }
                }
                this.localForm.fileArrays = this.localForm.fileArrays ?? []
              this.selectTemplate.entityMeasureUnit = this.localForm.applyUnit
                // this.$console(this.localForm)
            } else {
                this.localForm = { technicalId: '' }
                this.selectTemplate = { entityMeasureUnit : '套' }
                this.technologyTemplateList = []
                this.expandedKeys = []
                this.selectedKeys = []
            }
        }
    },
   async mounted(){
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('new_technique_use')
    },
    methods: {
      selectOrg(val) {
        if(val.length>1) {
            console.log('val',val)
          this.localForm.branchCompanyId = val[val.length - 2].orgId;
          this.localForm.projectId = val.at(-1).projectId;
        //   this.$refs.form.clearValidate('projectId')
        }
      },
        selectChange(e) {
            let res = this.technologyTemplateList.find((v) => v.technicalId === e)
            if (res) {
              this.selectTemplate = res
                this.localForm.treeId = res.treeId
            }
        },
        onChange(e) {
            const value = e.target.value
            if (!value) {
                this.autoExpandParent = true
                this.expandedKeys = this.$clone(this.expandedKeysTemp)
                this.searchValue = ''
            } else {
                const expandedKeys = this.dataList
                    .map((item) => {
                        if (item.title.indexOf(value) > -1) {
                            return this.getParentKey(item.key, this.treeData)
                        }
                        return null
                    })
                    .filter((item, i, self) => item && self.indexOf(item) === i)
                Object.assign(this, {
                    expandedKeys,
                    searchValue: value,
                    autoExpandParent: true
                })
            }
        },
        generateList(data) {
            for (let i = 0; i < data.length; i++) {
                const node = data[i]
                const key = node.key
                const title = node.title
                // this.dataList.push({ key, title: key })
                this.dataList.push({ key, title })
                if (node.children) {
                    this.generateList(node.children)
                }
            }
        },
        getParentKey(key, tree) {
            let parentKey
            for (let i = 0; i < tree.length; i++) {
                const node = tree[i]
                if (node.children) {
                    if (node.children.some((item) => item.key === key)) {
                        parentKey = node.key
                    } else if (this.getParentKey(key, node.children)) {
                        parentKey = this.getParentKey(key, node.children)
                    }
                }
            }
            return parentKey
        },
        async getTree() {
            return new Promise(async (resolve) => {
                this.getTreeLoading = true
                let res = await treeList()
                this.getTreeLoading = false
                if (res.code === this.SUCCESS_CODE) {
                    this.treeData = this.replaceList(res.data)
                    this.generateList(this.treeData)
                }
                resolve()
            })
        },
        replaceList(list) {
            return list.map((v) => {
                v.scopedSlots = { title: 'title' }
                v.key = v[this.replaceFields.key]
                v.title = v[this.replaceFields.title]
                if (v.children && v.children.length) {
                    v.children = this.replaceList(v.children)
                }
                return v
            })
        },
        onSelect(selectedKeys, info) {
            this.selectedKeys = selectedKeys
            this.localForm.technicalId = ''
            if (selectedKeys.length) {
                this.getTechnologyTemplateList(info.selectedNodes[0].data.props.id)
            } else {
                this.technologyTemplateList = []
            }
        },
        onExpand(expandedKeys) {
            this.expandedKeys = expandedKeys
            this.expandedKeysTemp = expandedKeys
            this.autoExpandParent = false
        },

        async getTechnologyTemplateList(treeId) {
            this.getTreeLoading = true
            let res = await getTechnologyTemplate(null, { pageNo: 1, pageSize: 10000, treeId, status: 1 })
            this.getTreeLoading = false
            if (res.code === this.SUCCESS_CODE) {
                this.technologyTemplateList = res.data
            }
        },
        handleOk(type) {
            this.setProcessConfig = null;
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                  this.submitApprovalConfirm(type==1?this.processConfig:6,async (flag)=>{
                    if(!flag) {
                      this.confirmLoading[type] = false
                      return
                    }
                    this.confirmLoading[type] = true
                    this.localForm.statusCode = type === 0 && this.localForm.statusCode === 3 ? 3 : type
                    let res
                    if (this.localForm.id) {
                        res = await editTechnology(this.localForm)
                    } else {
                        res = await addTechnology(this.localForm)
                    }
                    this.confirmLoading[type] = false
                    if (res.code === this.SUCCESS_CODE) {
                        this.$emit('ok')
                        this.$emit('update:visible',false)
                        this.$noticeSuccess((this.localForm.id ? '编辑' : '新增') + '成功')
                        if(type*1===1) {
                        //提交时，返回id
                            this.businessId = res.data.id;
                            this.setProcessConfig = this.processConfig;
                            return
                        }else{
                           this.handleCancel()
                        }
                    }
                  })
                } else {
                    this.$noticeWarning('请填写完整')
                }
            })
        },
        handleCancel() {
            this.$emit('update:visible', false)
            this.$refs.form.resetFields()
            this.localForm = { technicalId: '' }
            this.selectedKeys = []
        },
        closeSelectApprover(){
            this.handleCancel()
        }
    }
}
</script>


<style scoped>
    .limitText /deep/ .uploadName .ant-btn {
        max-width: 95%;
        white-space: pre-wrap;
        text-align: left;
        word-break: break-all;
    }
</style>
